package com.haibei.view;

import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.DrawTool;
import com.common.uitl.SharePersistent;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.common.uitl.ValidateTool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.MainActivity;
import com.haibei.activity.setting.ChangePersonInfoActivity;
import com.haibei.activity.setting.SettingActivity;
import com.haibei.activity.user.CollectArticleActivity;
import com.haibei.activity.user.CollectTopicActivity;
import com.haibei.activity.user.CollectWareActivity;
import com.haibei.activity.user.LoginActivity;
import com.haibei.activity.user.MessageActivity;
import com.haibei.activity.user.RegistActivity1;
import com.haibei.adapter.AnimationAdapter;
import com.haibei.adapter.bean.User;
import com.haibei.net.NetInterface;

/**
 * 个人中心页面
 * 
 * @author wangzy
 */
public class SubTabViewUserCenter extends SubTabView implements View.OnClickListener {

	private View relativeLayoutCover;
	private int INT_GO_LOGIN = 500;
	private int INT_GO_CHANGE_INFO = 501;
	private BaseTask mBaseTask;
	private ImageView imageViewHeader;

	private EditText mEditTextUserName;
	private EditText mEditTextPassWord;

	private View mViewLoginGo;
	private Button mButtonLogin;
	private final int INT_GO_RETIST1 = 1000;

	public SubTabViewUserCenter(MainActivity activity) {
		super(activity);
	}

	@Override
	public void initView() {
		this.mContentView = View.inflate(mActivity, R.layout.sub_tab_infocenter, null);
		this.relativeLayoutCover = findViewById(R.id.relativeLayoutCover);
		this.imageViewHeader = (ImageView) findViewById(R.id.imageViewHeader);
		findViewById(R.id.linearLayoutCareTopic).setOnClickListener(this);
		findViewById(R.id.linearLayoutGoodsCollect).setOnClickListener(this);// 收藏商品
		findViewById(R.id.linearLayoutCollectArticle).setOnClickListener(this);
//		findViewById(R.id.linearLayoutDiscountCoupon).setOnClickListener(this);
		findViewById(R.id.linearLayoutPersonInfo).setOnClickListener(this);
		findViewById(R.id.buttonSetting).setOnClickListener(this);
		findViewById(R.id.buttonLogout).setOnClickListener(this);
		findViewById(R.id.buttonMessage).setOnClickListener(this);
		findViewById(R.id.imageViewHeader).setOnClickListener(this);

		initLoginView();
		// this.relativeLayoutCover.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent i = new Intent();
		// i.setClass(getActivity(), LoginActivity.class);
		// getActivity().startActivityForResult(i, INT_GO_LOGIN);
		// }
		// });
		hideOrShowCover();
	}

	private void hideOrShowCover() {
		if (App.isLogin()) {
			this.relativeLayoutCover.setVisibility(View.GONE);
		} else {
			this.relativeLayoutCover.setVisibility(View.VISIBLE);// 登陆页面

		}
		fillUserInfo(App.getApp().getUser());
	}

	private void initLoginView() {
		mEditTextUserName = (EditText) findViewById(R.id.editTextUserName);
		mEditTextPassWord = (EditText) findViewById(R.id.editTextPassword);
		//================
		String uname = SharePersistent.getPerference(mActivity, App.KEY_USER);
		if (!StringUtils.isEmpty(uname)) {
			mEditTextUserName.setText(uname);
		}
		
		String pwd = SharePersistent.getPerference(mActivity, App.KEY_PWD);
		if (!StringUtils.isEmpty(pwd)) {
			mEditTextPassWord.setText(pwd);
		}
		// ================
		mViewLoginGo = findViewById(R.id.textViewLoginGo);
		mViewLoginGo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClass(mActivity, RegistActivity1.class);
				mActivity.startActivityForResult(i, INT_GO_RETIST1);
			}
		});
		mButtonLogin = (Button) findViewById(R.id.buttonLogin);
		mButtonLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkValue()) {
					login();
				}
			}
		});

	}

	@Override
	public void onShow() {
		getActivity().getSlidingMenu().setSlidingEnabled(false);
		hideOrShowCover();
		if (App.isLogin()) {// 展示用户名密码
			String uname = SharePersistent.getPerference(mActivity, App.KEY_USER);
			if (!StringUtils.isEmpty(uname)) {
				mEditTextUserName.setText(uname);
			}
			String pwd = SharePersistent.getPerference(mActivity, App.KEY_PWD);
			if (!StringUtils.isEmpty(pwd)) {
				mEditTextPassWord.setText(pwd);
			}
		}
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		Intent i = new Intent();

		switch (vid) {
		case R.id.imageViewHeader: {
			i.setClass(getActivity(), ChangePersonInfoActivity.class);
			getActivity().startActivityForResult(i, INT_GO_CHANGE_INFO);
		}
			break;
		case R.id.buttonSetting:
			Tool.startActivity(getActivity(), SettingActivity.class);
			break;
		case R.id.linearLayoutPersonInfo:
			i.setClass(getActivity(), ChangePersonInfoActivity.class);
			getActivity().startActivityForResult(i, INT_GO_CHANGE_INFO);
			break;
		case R.id.buttonLogout: {
			App.logout();
			hideOrShowCover();
		}
			break;
		case R.id.linearLayoutGoodsCollect: {
			// 收藏的商品
			i.setClass(getActivity(), CollectWareActivity.class);
			getActivity().startActivity(i);
		}
			break;
		case R.id.linearLayoutCollectArticle: {
			// 收藏的文章
			i.setClass(getActivity(), CollectArticleActivity.class);
			getActivity().startActivity(i);
		}
			break;
		case R.id.linearLayoutCareTopic: {
			// 关注的话题
			i.setClass(getActivity(), CollectTopicActivity.class);
			getActivity().startActivity(i);
		}
			break;
//		case R.id.linearLayoutDiscountCoupon: {
//			// 优惠劵
//			// getActivity().startActivity(i);
//		}
//			break;
		case R.id.buttonMessage: {
			i.setClass(getActivity(), MessageActivity.class);
			getActivity().startActivity(i);
		}
			break;
		default: {
			Tool.startActivity(getActivity(), CollectTopicActivity.class);
		}
			break;
		}
	}

	private void fillUserInfo(User u) {
		ImageView imageHeader = (ImageView) findViewById(R.id.imageViewHeader);
		ImageView imageSex = (ImageView) findViewById(R.id.imageViewSex);
		TextView textViewStage = (TextView) findViewById(R.id.textViewStage);
		TextView textViewUserName = (TextView) findViewById(R.id.textViewUserName);
		if (null != u) {
			updateUserIcon(u);
			imageSex.setImageResource((Integer.parseInt(u.getSex()) == User.MAN ? R.drawable.icon_sex_male : R.drawable.icon_sex_female));
			textViewStage.setText(u.getStageText(u.getStage(), u.getSex()));
			textViewUserName.setText(u.getNikename());
		} else {
			imageHeader.setImageResource(R.drawable.icon_header_default);
			textViewStage.setText("");
			textViewUserName.setText("");
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		hideOrShowCover();
		if (requestCode == INT_GO_CHANGE_INFO) {
			if (Activity.RESULT_OK == resultCode) {
				User u = App.getApp().getUser();
				if (null != u) {
					login(u);
				}
			}
		}
	}

	private void updateUserIcon(final User u) {
		BaseTask btask = new BaseTask(new NetCallBack() {
			@Override
			public void onFinish(NetResult result) {
				if (null != result) {
					try {
						Bitmap bitmap = (Bitmap) result.getData()[0];
						imageViewHeader.setImageBitmap(DrawTool.toRoundBitmap(bitmap));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				try {
					NetResult netResult = new NetResult();
					String headerPoraint = u.getHeadPortrait();
					if (!StringUtils.isEmpty(headerPoraint)) {
						String urlStr = NetInterface.img_host + headerPoraint;
						URL url = new URL(urlStr);
						InputStream inputStream = url.openStream();
						Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
						if (null != bitmap) {
							Object data[] = { bitmap };
							netResult.setData(data);
							return netResult;
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		});
		btask.execute(new HashMap<String, String>());
	}

	private void login(User u) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("username", u.getUsername());
		hmap.put("password", u.getPassword());
		getLoginTask().execute(hmap);
	}

	private void login() {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("username", getUserName());
		hmap.put("password", getPassword());
		getLoginTask().execute(hmap);
	}

	private boolean checkValue() {
		if (!ValidateTool.checkEmail(getUserName())) {
			Tool.ToastShow(mActivity, "请输入正确的email地址");
			// mEditTextUserName.setError("请输入正确的email地址！");
			return false;
		}
		if (StringUtils.isEmpty(getPassword()) || getPassword().length() < 6) {
			Tool.ToastShow(mActivity, "请输入至少6位密码");
			// mEditTextUserName.setError("请输入密码");
			return false;
		}
		return true;
	}

	private String getUserName() {
		String text = mEditTextUserName.getText().toString();
		return StringUtils.isEmpty(text) ? "" : text;
	}

	private String getPassword() {
		String text = mEditTextPassWord.getText().toString();
		return StringUtils.isEmpty(text) ? "" : text;
	}

	private BaseTask getLoginTask() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				mActivity.showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				mActivity.hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						User u = (User) result.getData()[0];
						App.getApp().setUser(u);
						fillUserInfo(u);
						if (relativeLayoutCover.getVisibility() == View.VISIBLE) {
							Animation ani = AnimationUtils.loadAnimation(mActivity, R.anim.slide_bottom_out);
							ani.setAnimationListener(new AnimationAdapter() {
								public void onAnimationEnd(Animation animation) {
									relativeLayoutCover.setVisibility(View.GONE);
								};
							});
							relativeLayoutCover.startAnimation(ani);
						}
					} else {
						Tool.ToastShow(mActivity, result.getMessage());
					}
				} else {
					Tool.ToastShow(mActivity, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.login(mActivity, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}
}
